import { getEvent, GlobalEvent } from './events.js';
import { createRequire } from 'module';

const require = createRequire(import.meta.url);
export type KeyState = {
  isToggled: boolean;
  isDown: boolean;
};
const addon: {
  setEventListener: (
    listener: (type: number, action: number, value: number, x: number, y: number) => void
  ) => void;
  state: (keyId: number) => KeyState;
  apiType: string;
} = require('../build/Release/global-recorder.node');

export type GlobalEventListener = (event: GlobalEvent) => void;
const eventListeners = new Set<GlobalEventListener>();

addon.setEventListener((...args) => {
  try {
    const event: GlobalEvent = getEvent(...args);
    console.log(event);
    callListeners(event);
  } catch (e) {
    console.error(e);
  }
});
export function state(keyId: number): KeyState {
  return addon.state(keyId);
}
export function addEventListener(cb: GlobalEventListener): () => void {
  eventListeners.add(cb);
  return () => eventListeners.delete(cb);
}
function callListeners(event: GlobalEvent) {
  eventListeners.forEach((cb) => cb(event));
}
